<script>
import MAIN_STORE from "@/store/store.js";
import { CloseBold, Location } from "@element-plus/icons-vue";
import { MeasureBuffer } from "@/utils/Measure";
import mitt from "mitt";
import { ref, reactive } from "vue";
import SelfDraggable from '@/components/Draggable/Draggable.vue';
let mittBus = null;
function getListData(data) {
  const listData = Object.keys(data || {}).map(v => { return { key: v, value: data[v] } })
  return listData
}
export default {
  /**
   * 缓冲区查询
   */
  name: "search-buffer",
  components: { CloseBold, Location, SelfDraggable },
  data() {
    return {
      dialogDrawer: false,
      // 表单
      realForm: {
        radius: 50,
        type: 'point'
      },
      // 是否正在绘制
      isPainting: false,
      // 是否有查询的数据
      dataForPaint: [],
      bufferForm: {
        polygon: null
      },
      // 选中的项 id
      selectedId: null,
      listData: []
    };
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  computed: {
  },
  watch: {
    'realForm.radius': (nV) => {
      const ins = MeasureBuffer.getIns();
      ins && ins.resetRadius({
        radius: nV
      });
    },
    visible: function (nV) {
      if (!nV) {
        const ins = MeasureBuffer.getIns();
        ins && ins.destroy();
        this.dataForPaint = [];
        this.selectedId = null;
      }
    }
  },
  mounted() {
  },
  beforeUnmount() {
    mittBus && mittBus.all.clear();
    mittBus = null;
    const ins = MeasureBuffer.getIns();
    ins && ins.destroy();
    this.dataForPaint = [];
    this.selectedId = null;
  },
  methods: {
    // 开始选中点
    selectPoint() {
      this.dataForPaint = [];
      this.bufferForm.polygon = null;
      // 如果正在绘制
      if (this.isPainting) {
        // 结束绘制
        this.isPainting = false;
        // 销毁绘制实例
        const ins = MeasureBuffer.getIns();
        ins && ins.destroy();
      } else {
        // 开始绘制
        this.isPainting = true;
        // 生成绘制实例
        let ins = MeasureBuffer.getIns();
        if (!ins) {
          mittBus = mitt();
          ins = MeasureBuffer.create({
            map: MAIN_STORE.GLOBAL_MAP_INS,
            bufferRadius: this.realForm.radius,
            mittBus: mittBus
          });
          ins.mittBus.on('polygon', ({ polygon }) => {
            this.bufferForm.polygon = polygon;
            this.queryBuffer()
          })
        }
      }
    },
    // 数据查询
    queryBuffer() {
      if (!this.bufferForm.polygon) { return }
      // 应用集合查询
      const bufferParam = new ol.supermap.GetFeaturesByGeometryParameters({
        datasetNames: ["pipeline_4326:ALL_POINT"],
        geometry: this.bufferForm.polygon,
        spatialQueryMode: "INTERSECT",
        toIndex: 9
      });
      const url = 'http://localhost:8090/iserver/services/data-pipeline-1128/rest/data';
      new ol.supermap.FeatureService(url).getFeaturesByGeometry(bufferParam).then(serviceResult => {
        // console.log(serviceResult.result.features, 'serviceResult.result.features')
        this.dataForPaint = serviceResult.result.features.features;
      });
    },
    close() {
      this.isPainting = false;
      this.$emit('close')
    },
    getDetail(data) {
      const ins = MeasureBuffer.getIns();
      if (!ins) { return }
      this.listData = getListData(data.properties)
      this.dialogDrawer = true;
      // 设置用于定位的 overlay 的详情
      // ins.showDetail({
      //   detail: ref(Math.random()),
      // });
      this.getPos(data, this.listData)
    },
    // 定位
    getPos(data, listData) {
      this.selectedId = data.id;
      const coordinates = data.geometry.coordinates;
      this.$store.commit("LOCATION_CERTAIN_VIEW", {
        position: coordinates,
        accu: true
      });
      const ins = MeasureBuffer.getIns();
      if (!ins) { return }
      // 设置用于定位的 overlay
      ins.setOverlayForLocate({
        coordinate: coordinates,
        listData: listData || getListData(data.properties)
      });
    },
    closeDrawer() {
      this.dialogDrawer = false;
    }
  },
};
</script>

<template>
  <div class="search-buffer">
    <div class="header">
      <span>缓冲区查询</span>
      <div class="icon-area hover-pointer" @click="close">
        <CloseBold></CloseBold>
      </div>
    </div>
    <el-form size="small" inline :model="realForm" label-width="auto">
      <el-form-item label="半径（M）">
        <el-input-number @keydown.enter.native.prevent="() => { }" v-model="realForm.radius" :min="1" :max="1000"
          :step="10" />
      </el-form-item>
      <el-form-item label="类型">
        <el-radio-group :disabled="isPainting" v-model="realForm.type">
          <el-radio-button label="管线" value="line" />
          <el-radio-button label="管点" value="point" />
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button text size="small" type="primary" @click="selectPoint">
          {{ isPainting ? '取消' : '选择缓冲点' }}
        </el-button>
        <el-button :disabled="!bufferForm.polygon" size="small" type="primary" @click="queryBuffer">
          查询
        </el-button>
      </el-form-item>
    </el-form>
    <div>
      <el-table :data="dataForPaint" stripe style="width: 100%" :empty-text="'暂无数据'">
        <el-table-column :prop="'properties.WYDH'" label="外业点号" width="120" />
        <el-table-column :prop="'properties.物探点号'" label="物探点号" width="120" />
        <el-table-column :prop="'properties.GXXZ'" label="类型" width="100" />
        <el-table-column :prop="'properties.井盖材质'" label="材质" width="100" />
        <el-table-column :prop="'properties.所在道路'" label="道路名称" />
        <el-table-column fixed="right" label="操作" width="100">
          <template #default="scope">
            <el-button link :type="selectedId === scope.row.id ? 'success' : 'primary'" size="small"
              @click="getDetail(scope.row)">详情</el-button>
            <el-button link :type="selectedId === scope.row.id ? 'success' : 'primary'" size="small"
              @click="getPos(scope.row)">
              定位
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-drawer v-model="dialogDrawer" title="详细信息" :before-close="closeDrawer" direction="rtl"
      class="demo-drawer">
      <div class="demo-drawer__content">
        <el-descriptions :column="2" title="" border>
          <el-descriptions-item v-for="(item, index) in listData" :key="index" :label="item.key">{{ item.value
            }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-drawer>
  </div>
</template>
<style>

</style>
<style lang="less" scoped>
:deep(.demo-drawer .el-drawer__body) {
  --el-drawer-padding-primary: 0;
}
:deep(.demo-drawer .el-drawer__header) {
  margin-bottom: 20px;
}
.search-buffer {
  &>.header {
    font-size: 16px;
    color: #2168b2;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    &>.icon-area {
      width: 20px;
      height: 20px;
    }
  }
}
</style>
